package com.hwz.gulimall.product.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.hwz.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import com.hwz.gulimall.product.entity.CategoryEntity;
import com.hwz.gulimall.product.service.CategoryService;
import com.hwz.common.utils.PageUtils;
import com.hwz.common.utils.R;



/**
 * 商品三级分类
 *
 * @author hwz
 * @email 1281561921@qq.com
 * @date 2025-05-27 23:40:51
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 获取三级分类列表的树状结构
     */
    @GetMapping("/list/tree")
    public R list(){
//        PageUtils page = categoryService.queryPage(params);
        List<CategoryEntity> tree = categoryService.listWithTree();
        return R.ok().put("page", tree);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("category", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category){


        if (category.getName() != null){
            if (category.getCatId() == null) {
                categoryService.save(category);
            }else {
                categoryService.updateById(category);
            }
        }

        return R.ok();
    }

    /**
     * 修改
     *
     * //    @Caching(evict = {
     * //            @CacheEvict(value = "catalogJson",key = "'getFirstLevelCategories'"),
     * //            @CacheEvict(value = "catalogJson",key = "'getCatalogJson'")
     * //    })
     */
    @RequestMapping("/update")
    @CacheEvict(value = "catalogJson",allEntries = true)  //更新后清除缓存
    public R update(@RequestBody CategoryEntity category){
		categoryService.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        return R.ok();
    }
//    批量修改
    @PostMapping("/batchUpdate")
    public R batchUpdate(@RequestBody List<CategoryEntity>  categories){
        categoryService.updateBatchById(categories);
        return R.ok();
    }


    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
//        System.out.println(catIds);
		categoryService.removeByIds(Arrays.asList(catIds));
        return R.ok();
    }

}
